<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="50%"
    title="新增"
    :dialog-style="{ top: '20px' }"
    :footer="null"
  >
    <div v-if="visible" v-permission="['promotions:fullreduction:add']" v-loading="loading">
      <a-form
        ref="form"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
        :model="formData"
        :rules="rules"
      >
        <a-divider>基本信息</a-divider>
        <a-form-item label="活动名称" name="name">
          <a-input v-model:value="formData.name" max-length="20" allow-clear />
        </a-form-item>
        <cycle-form
          ref="cycleForm"
          v-model:begin-date="formData.beginDate"
          v-model:end-date="formData.endDate"
          v-model:cycle-flag="formData.cycleFlag"
          v-model:cycle-type="formData.cycleType"
          v-model:cycle-time-group="formData.cycleTimeGroup"
          v-model:cycle-time-rule="formData.cycleTimeRule"
        />
        <a-form-item label="适用人群" name="allMemberLevel">
          <a-row>
            <a-col :span="24">
              <div style="padding-top: 5px">
                <a-radio-group
                  v-model:value="formData.allMemberLevel"
                  @change="
                    () => {
                      formData.memberLevelId = [];
                    }
                  "
                >
                  <a-radio
                    v-for="item in $enums.MEMBER_LEVEL_TYPE.values()"
                    :key="item.code"
                    :value="item.code"
                    >{{ item.desc }}</a-radio
                  >
                </a-radio-group>
              </div>
            </a-col>
          </a-row>
          <a-row v-if="formData.allMemberLevel === 3">
            <a-col :span="24">
              <div style="padding-top: 5px">
                <member-level-selector
                  v-model:value="formData.memberLevelId"
                  :multiple="true"
                  :show-sum="true"
                />
              </div>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="共享优惠">
          <a-space>
            <a-checkbox v-model:checked="formData.useCoupon">优惠券</a-checkbox>
            <a-checkbox v-model:checked="formData.useFulldiscount">满折</a-checkbox>
            <a-checkbox v-model:checked="formData.useFullprice">特价</a-checkbox>
            <a-checkbox v-model:checked="formData.useFullgiftactivity">满赠</a-checkbox>
          </a-space>
        </a-form-item>
        <a-divider>参与商品及特价设置</a-divider>
        <a-form-item label="参与门店" name="allShop">
          <a-row>
            <a-col :span="24">
              <div style="padding-top: 5px">
                <a-radio-group v-model:value="formData.allShop">
                  <a-radio :value="true">全部门店</a-radio>
                  <a-radio :value="false">指定门店</a-radio>
                </a-radio-group>
              </div>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item v-if="!formData.allShop" label=" " :colon="false" name="shopId">
          <shop-selector v-model:value="formData.shopId" :multiple="true" :show-sum="true" />
        </a-form-item>
        <a-form-item label="参与商品" name="allProduct">
          <a-row>
            <a-col :span="24">
              <div style="padding-top: 5px">
                <a-radio-group
                  v-model:value="formData.allProduct"
                  @change="
                    () => {
                      if (formData.allProduct) {
                        formData.productId = [];
                      }
                    }
                  "
                >
                  <a-radio :value="true">全部商品</a-radio>
                  <a-radio :value="false">指定商品</a-radio>
                </a-radio-group>
              </div>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item v-if="!formData.allProduct" label=" " :colon="false" name="productId">
          <product-selector v-model:value="formData.productId" :multiple="true" :show-sum="true" />
        </a-form-item>
        <a-form-item label="活动类型" name="reductionType">
          <a-radio-group v-model:value="formData.reductionType">
            <a-radio :value="1">满N元减</a-radio>
            <a-radio :value="2">满N件减</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="优惠模式" name="promType">
          <a-radio-group
            v-model:value="formData.promType"
            @change="
              () => {
                formData.promItem = [{}];
              }
            "
          >
            <a-radio :value="1">阶梯递减</a-radio>
            <a-radio :value="2">循环满减</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label=" " :colon="false">
          <a-row :gutter="[12, 12]" style="background-color: rgb(245, 248, 250)">
            <a-col :span="24" v-for="(item, index) in formData.promItem" :key="index">
              <a-space>
                <div>满</div>
                <div>
                  <a-form-item
                    label=""
                    :name="['promItem', index, 'achieve']"
                    :rules="[{ required: true }]"
                    no-style
                  >
                    <a-input-number
                      style="width: 150px"
                      :addon-after="formData.reductionType === 1 ? '￥' : '件'"
                      :precision="formData.reductionType === 1 ? 2 : 0"
                      min="0"
                      v-model:value="item.achieve"
                    />
                  </a-form-item>
                </div>
                <div>减</div>
                <div>
                  <a-form-item
                    label=""
                    :name="['promItem', index, 'reduce']"
                    :rules="[{ required: true }]"
                    no-style
                  >
                    <a-input-number
                      style="width: 150px"
                      addon-before="￥"
                      :precision="2"
                      min="0"
                      v-model:value="item.reduce"
                    />
                  </a-form-item>
                </div>
                <div>
                  <a-button
                    v-if="formData.promType === 1"
                    type="link"
                    @click="
                      () => {
                        formData.promItem.splice(index, 1);
                      }
                    "
                    danger
                  >
                    删除
                  </a-button>
                </div>
              </a-space>
            </a-col>
            <a-col :span="24">
              <a-button
                v-if="formData.promType === 1"
                style="width: 405px"
                type="dashed"
                @click="
                  () => {
                    formData.promItem.push({});
                  }
                "
                block
              >
                新增
              </a-button>
            </a-col>
          </a-row>
        </a-form-item>
        <div class="form-modal-footer">
          <a-space>
            <a-button type="primary" :loading="loading" html-type="submit" @click="submit"
              >保存</a-button
            >
            <a-button :loading="loading" @click="closeDialog">取消</a-button>
          </a-space>
        </div>
      </a-form>
    </div>
  </a-modal>
</template>
<script>
  import { defineComponent } from 'vue';
  import * as api from '@/api/promotions/fullreduction';
  import dayjs from 'dayjs';
  import AButton from '@/components/Button/src/BasicButton.vue';
  import CycleForm from '@/views/promotions/cycleForm.vue';
  import MemberLevelSelector from '@/components/Selector/src/MemberLevelSelector.vue';
  import ShopSelector from '@/components/Selector/src/ShopSelector.vue';
  import { MEMBER_LEVEL_TYPE } from '@/enums/biz/memberLevelType';
  import ProductSelector from '@/components/Selector/src/ProductSelector.vue';

  export default defineComponent({
    components: {
      ProductSelector,
      ShopSelector,
      MemberLevelSelector,
      CycleForm,
      AButton,
    },
    data() {
      return {
        // 是否可见
        visible: false,
        // 是否显示加载框
        loading: false,
        presets: [
          { label: '今天', value: [dayjs(), dayjs()] },
          { label: '最近3天', value: [dayjs(), dayjs().add(3, 'day')] },
          { label: '最近7天', value: [dayjs(), dayjs().add(7, 'day')] },
          { label: '最近30天', value: [dayjs(), dayjs().add(30, 'day')] },
        ],
        // 表单数据
        formData: {},
        // 表单校验规则
        rules: {
          name: [{ required: true, message: '请输入促销活动名称' }],
          beginDate: [{ required: true, message: '请输入促销活动开始时间' }],
          endDate: [{ required: true, message: '请输入促销活动结束时间' }],
          cycleFlag: [{ required: true, message: '请输入活动期间是否周期执行' }],
          cycleType: [{ required: true, message: '请输入周期类型(1:每天; 2:每周; 3:每月)' }],
          cycleTimeGroup: [{ required: true, message: '请输入周期执行时间段' }],
          cycleTimeRule: [{ required: true, message: '请输入周期执行规则' }],
          memberLevelId: [{ required: true, message: '请输入会员等级id' }],
          allProduct: [{ required: true, message: '请输入是否全部商品参与' }],
          productId: [{ required: true, message: '请输入商品id' }],
          useCoupon: [{ required: true, message: '请输入是否可使用优惠券' }],
          useFulldiscount: [{ required: true, message: '请输入是否可参与满折' }],
          useFullprice: [{ required: true, message: '请输入是否可参与特价' }],
          useFullgiftactivity: [{ required: true, message: '请输入是否可参与满赠' }],
          allShop: [{ required: true, message: '请输入是否全部门店' }],
          shopId: [{ required: true, message: '请输入门店id' }],
          reductionType: [{ required: true, message: '请输入满减活动类型' }],
          promType: [{ required: true, message: '请输入优惠类型' }],
        },
      };
    },
    computed: {
      MEMBER_LEVEL_TYPE() {
        return MEMBER_LEVEL_TYPE;
      },
      range_date() {
        return [
          this.formData.beginDate ? dayjs(this.formData.beginDate) : null,
          this.formData.endDate ? dayjs(this.formData.endDate) : null,
        ];
      },
    },
    created() {
      // 初始化表单数据
      this.initFormData();
    },
    methods: {
      dayjs,
      // 打开对话框 由父页面触发
      openDialog() {
        this.visible = true;

        this.$nextTick(() => this.open());
      },
      // 关闭对话框
      closeDialog() {
        this.visible = false;
        this.$emit('close');
      },
      // 初始化表单数据
      initFormData() {
        this.formData = {
          name: '',
          beginDate: '',
          endDate: '',
          cycleFlag: false,
          cycleType: 1,
          cycleTimeGroup: [
            {
              beginTime: '',
              endTime: '',
            },
          ],
          cycleTimeRule: [],
          promDiscount: {},
          allMemberLevel: 1,
          memberLevelId: '',
          allBuyLimit: false,
          cycleBuyLimit: 0,
          allProduct: true,
          productId: [],
          useCoupon: false,
          useFulldiscount: false,
          useFullprice: false,
          useFullgiftactivity: false,
          allShop: true,
          shopId: [],
          reductionType: 1,
          promType: 1,
          promItem: [{}],
        };
      },
      // 提交表单事件
      submit() {
        let formValidPromise = this.$refs.form.validate();
        let cycleFormValidPromise = this.$refs.cycleForm.validateForm();
        Promise.allSettled([formValidPromise, cycleFormValidPromise]).then((results) => {
          if (results[0].status === 'fulfilled' && results[1].status === 'fulfilled') {
            api
              .create({
                ...this.formData,
                beginDate: this.formData.beginDate + ' 00:00:00',
                endDate: this.formData.endDate + ' 23:59:59',
                cycleTimeGroup: JSON.stringify(this.formData.cycleTimeGroup),
                cycleTimeRule: JSON.stringify(this.formData.cycleTimeRule),
                memberLevelId: JSON.stringify(this.formData.memberLevelId),
                productId: JSON.stringify(this.formData.productId),
                shopId: JSON.stringify(this.formData.shopId),
                promItem: JSON.stringify(this.formData.promItem),
              })
              .then(() => {
                this.$msg.createSuccess('新增成功！');
                this.$emit('confirm');
                this.visible = false;
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },
      // 页面显示时触发
      open() {
        // 初始化表单数据
        this.initFormData();
      },
    },
  });
</script>
